import json
import pdb

from django.core import serializers
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from reportlab.lib.randomtext import objects

from apps.translator.models import Translation, Config


@csrf_exempt
def call_back(request):
    # 通过task_id会写翻译状态
    task_id = request.POST.get('task_id')
    output_file_path = request.POST.get('output_file_path')
    # 处理输出路径
    # D:/code/openai_translator_v2/openai_translator/static/results/20250215/test.pdf
    relative_output_file_path = output_file_path.split("openai_translator\\")[1]
    ob = Translation.objects.get(id=int(task_id))
    ob.result_file = relative_output_file_path
    ob.status = '翻译完成'
    ob.save()
    response = {"msg": "success", "task_id": task_id, "path": relative_output_file_path}
    print(response)
    return JsonResponse(response)


def list_config(request):
    configs = Config.objects.all()
    data = serializers.serialize('json', queryset=configs)
    response = {"msg": "success", "configs": json.loads(data)}
    return JsonResponse(response)


def list_translation(request):
    translations = Translation.objects.all()
    # 分页
    page_number = request.GET.get("page")
    if not page_number:
        page_number = 10
    paginator = Paginator(translations, page_number)  # Show 25 contacts per page.
    page_obj = paginator.get_page(page_number)
    data = serializers.serialize('json', queryset=page_obj)
    response = {"msg": "success", "translations": json.loads(data)}
    return JsonResponse(response)
